package com.laboratory.eventlistenerlearning.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Bean("asyncExecutor")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(8); // 核心线程数
        executor.setMaxPoolSize(16); // 最大线程数
        executor.setKeepAliveSeconds(60); // 线程空闲时间
        executor.setQueueCapacity(512); // 队列容量
        executor.setThreadNamePrefix("Async-"); // 线程名称前缀
        executor.setAwaitTerminationSeconds(60); // 等待任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true); // 线程池关闭时等待所有任务完成
        executor.setAllowCoreThreadTimeOut(true); // 允许核心线程超时
        executor.initialize(); // 初始化线程池
        return executor;
    }

    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> System.err.println("[ASYNC-ERROR] method=" + method.getName() + ", ex=" + ex.getMessage());
    }

}
